package com.xieyong.leetcode;

import java.util.ArrayList;

public class Leetcode2033 {
    public static void main(String[] args) {
        Leetcode2033 leetcode2033 = new Leetcode2033();
        int[][] grid = {{141,105,69,273,681,105,933,417,309},{921,657,945,717,885,57,453,921,897},{681,345,657,177,897,609,465,801,429},{681,993,741,885,105,981,477,249,921},{369,885,945,537,45,861,381,345,417},{849,849,477,513,297,609,561,177,801},{561,417,129,585,621,561,261,153,501},{249,777,969,249,357,393,93,321,573},{525,813,381,909,825,297,681,345,813}};
        int i = leetcode2033.minOperations(grid, 12);
        System.out.println(i);

    }


    public int minOperations(int[][] grid, int x) {
        int len = grid.length * grid[0].length;
        ArrayList<Integer> list = new ArrayList<>();
        if(len == 1) {
            return 0;
        }
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                list.add(grid[i][j]);
            }
        }
        list.sort(Integer::compare);
        int mid = list.get(len / 2);
        int result = 0;
        for(int i = 0; i < list.size(); i++){
            int k = Math.abs(list.get(i) - mid);
            if(k % x == 0) {
                result += k / x;
            } else {
                return -1;
            }
        }
        return result;
    }
}
